{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#This has examples of how to build and xml file in python and call gdal.translate as an external command. \n",
    "\n",
    "https://github.com/nasa-gibs/gibs-ml/blob/master/download_data.py\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from datetime import datetime, time, date\n",
    "import os\n",
    "import subprocess\n",
    "sys.path.append('/home/jovyan/overcast/gibs-ml')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### This is from a machine learning repo that can be found at https://github.com/nasa-gibs/gibs-ml It is used to build the XML file used in gdalwarp to provide the input data "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from gibs_layer import GIBSLayer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Set up data to download "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# select either True Color or Bands367\n",
    "#layer_name='VIIRS_SNPP_CorrectedReflectance_BandsM11_I2_I1'\n",
    "type='TrueColor'\n",
    "#type='Band367'\n",
    "layer_name='MODIS_Terra_CorrectedReflectance_'+type\n",
    "#layer_name='MODIS_Terra_CorrectedReflectance_Bands367'\n",
    "# select date to download \n",
    "date=\"2019-06-11\"\n",
    "# select directory where output data will be stored\n",
    "output_dir='/home/jovyan/shared/data-overcast/modis/'\n",
    "#output_dir=\"./\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Output will be written to:  /home/jovyan/shared/data-overcast/modis/modis.BEAUFORT.20190611.TrueColor.tif\n"
     ]
    }
   ],
   "source": [
    "# output projection parameters Tthis needs to be tuned for the specfic region. A bit messy. \n",
    "region='BEAUFORT'\n",
    "tile_resolution='250m'\n",
    "proj_str =\"'+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-145 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'\" \n",
    "te_str = '-800000 -2500000 1200000 -400000'\n",
    "tr_str = '250 250'\n",
    "\n",
    "# that's the input projection \n",
    "epsg='3413'\n",
    "# set up a GIBS layer used to build the input XML file \n",
    "layer = GIBSLayer.get_gibs_layer(layer_name)\n",
    "get_date = datetime.strptime(date, \"%Y-%m-%d\")\n",
    "datestring = get_date.strftime(\"%Y-%m-%d\")\n",
    "outfile='modis.'+region+'.'+datestring.replace(\"-\",\"\")+ \".\"+type+'.tif' # needs to be changed so that the type is reflected in the name\n",
    "outpath = os.path.join(output_dir, outfile)\n",
    "print(\"Output will be written to: \",outpath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Generate the XML file used as input"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "layer.generate_xml(protocol=\"tms\", epsg=epsg, tile_resolution=tile_resolution, datestring=datestring)\n",
    "xml=layer.gibs_xml"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The date/time data in the xml string produced needs to be preplaced with the actual date/time\n",
    "xml = xml.replace(\"{Time}\", datestring)\n",
    "xml = xml.rstrip()  # remove all trailing whitespace\n",
    "# write output to a temporary xml file \n",
    "with open(\"temp.xml\", \"w\") as f:\n",
    "    f.write(xml)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "# build the command to pass to gdalwarp\n",
    "cmd_list = [\"gdalwarp\",\"-overwrite\",\"-t_srs\",proj_str,\"-te\",te_str,\"-tr\",tr_str,\"temp.xml\", outpath]\n",
    "cmd= ' '.join(cmd_list) # this makes it a single string. Different versions of subprocess.Popen seem to require eithe rlists or strings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### create a subprocess to run gdal... this could probably be replaced by using the Python gdal bindings, but I looked and it seems very complicated. This is easier though not as clean"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 b'Creating output file that is 8000P x 8400L.\\nProcessing temp.xml [1/1] : 0...10...20...30...40...50...60...70...80...90...100 - done.\\n' b''\n",
      "Done Writing File : /home/jovyan/shared/data-overcast/modis/modis.BEAUFORT.20190611.TrueColor.tif\n"
     ]
    }
   ],
   "source": [
    "process = subprocess.Popen(cmd,shell='True',stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n",
    "out,err = process.communicate()\n",
    "print(process.returncode, out,err, )\n",
    "print(\"Done Writing File :\", outpath)\n",
    "# remove temporary file.. Return condition should be checked\n",
    "os.remove(\"temp.xml\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Above needs some more error checking"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:notebook] *",
   "language": "python",
   "name": "conda-env-notebook-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
